<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";

const { pageData, roleMap } = useData();
import {
  deleteData,
  getDataByPage,
  downloadTemplate,
  exportData,
  importData,
  clearData
} from "@/api/modules/dynamic-camouflage/network-config";
import UpdateForm from "./components/UpdateForm/index.vue";
import ConfigForm from "./components/ConfigForm/index.vue";

const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {},
  responseKey: {
    list: "result.data",
    total: "result.total"
  }
});

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize
    }
  });
}

loadDataCb();

function reloadDataCb() {
  reloadData();
  loadData({
    api: getDataByPage,
    sendData: {
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize
    }
  });
}

loadDataCb();

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import moment from "moment";
import { ElMessage, ElMessageBox } from "element-plus";

const { deleteHandler, idList } = useDelete();

async function deleteCb(id) {
  await deleteHandler({
    api: deleteData,
    multiple: false,
    sendData: {
      id: [id]
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  idList.value = data.rowList.map(item => item.userId);
}

async function templateOperate(type) {
  const urlDownload = function (url, name) {
    var a = document.createElement("a");
    // console.log(url)
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  };
  if (type === "export") {
    const res = await exportData();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `network_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `network_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}

async function clear() {
  await ElMessageBox.confirm("您确定清空当前数据吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  });
  await clearData()
  ElMessage.success("操作成功")
  reloadDataCb();
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <BaseCollapse class="collapse-no-content" title="虚拟网络">
        <template #header>
          <div class="h-box justify-end mg-b-sm">
            <el-dropdown :hide-on-click="false">
              <div>
                <BaseButton type="import_icon_text" />
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <div style="text-align: center" @click="templateOperate('download')">下载模板</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div style="text-align: center" @click="templateOperate('import')">导入</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <BaseButton @click="templateOperate('export')" class="mg-l-sm" type="export_icon_text" />
            <UpdateForm @success="loadDataCb()">
              <BaseButton class="mg-l-sm" type="add_icon_text" />
            </UpdateForm>

            <BaseButton @click="clear()" type="clear_all_icon_text" />
            <BaseButton @click="reloadDataCb()" type="refresh_icon_text" />
          </div>
        </template>
      </BaseCollapse>
    </template>
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="false"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      @select="selectCb"
    >
      <template #6Default="{ data }">
        {{ data.row["6"] && data.row["6"] != "undefined" ? data.row["6"] : "" }}
      </template>
      <template #3Default="{ data }">
        <span v-if="data.row['3'] == 1">C类</span>
        <span v-if="data.row['3'] == 2">B类</span>
        <span v-if="data.row['3'] == 3">A类</span>
        <span v-if="data.row['3'] == 4">自定义</span>
      </template>
      <template #operationDefault="{ data }">
        <ConfigForm
          @success="loadDataCb"
          :row-data="{
            id: data.row[data.row.length - 1].replace('/', ''),
            name: data.row[1],
            iprange: data.row[2].split('/')[0],
            iprangeSux: data.row[2].split('/')[1],
            gateway: data.row[4],
            description: data.row[6]
          }"
        >
          <base-button type="config_icon_text"></base-button>
        </ConfigForm>
        <UpdateForm
          :row-data="{
            id: data.row[data.row.length - 1].replace('/', ''),
            name: data.row[1],
            iprange: data.row[2].split('/')[0],
            iprangeSux: data.row[2].split('/')[1],
            gateway: data.row[4],
            description: data.row['6'] && data.row['6'] != 'undefined' ? data.row['6'] : ''
          }"
          :title="`编辑虚拟网络`"
          @success="loadDataCb"
        >
          <base-button type="edit_text"></base-button>
        </UpdateForm>
        <base-button
          v-if="username != data.row[1]"
          @click="deleteCb(data.row[data.row.length - 1].replace('/', ''))"
          type="del_text"
        ></base-button>
      </template>
    </he-table>
  </BaseUpDown>
</template>
